package com.winning.pmph.ctrl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.winning.pmph.entity.*;
import com.winning.pmph.mapper.HistoryMapper;
import com.winning.pmph.service.*;
import com.winning.pmph.utils.*;
import com.winning.pmph.vo.FileVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.SneakyThrows;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.commons.lang.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.springframework.core.io.ClassPathResource;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * @author 刘亚飞
 * @Description
 * @create 2020-10-20 19:08
 */
@Api(value = "知识库管理/流程图")
@RestController
@RequestMapping("/pmph/action/flowChartAction")
public class FlowChartCtrl {
    @Resource
    private FlowChartService flowChartService;
    @Resource
    private ReleasedFlowChartService releasedFlowChartService;
    @Resource
    private RuleService ruleService;
    @Resource
    private RuleItemService ruleItemService;
    @Resource
    private HistoryMapper historyMapper;
    @Resource
    private FilePath filePath;
    @Resource
    private TaskItemService taskItemService;

    @ApiOperation(value = "selectBelongingItemsData", notes = "流程图获取归属项目接口")
    @GetMapping("selectBelongingItemsData")
    public List<Map<String, String>> selectBelongingItemsData() {
        return getDropDownData("11");
    }

    @ApiOperation(value = "selectScienceData", notes = "流程图获取科学分类接口")
    @GetMapping("selectScienceData")
    public List<Map<String, String>> selectScienceData() {
        return getDropDownData("13");
    }

    /**
     * 取得流程图中下拉框对应值
     *
     * @param ruleId
     */
    private List<Map<String, String>> getDropDownData(String ruleId) {
        List<RuleItem> list = ruleItemService.lambdaQuery().eq(RuleItem::getRuleId, ruleId).list();
        List<Map<String, String>> resultList = Lists.newArrayList();
        list.forEach(t -> {
            Map<String, String> map = Maps.newConcurrentMap();
            map.put("value", t.getId());
            map.put("label", t.getName());
            resultList.add(map);
        });
        return resultList;
    }

    @ApiOperation(value = "deleteById", notes = "流程图列表删除接口")
    @GetMapping("deleteById")
    public void deleteById(String id) {
        flowChartService.deleteById(id);
    }

    @ApiOperation(value = "uploadFile", notes = "流程图编辑页面上传图片并维护静态资源接口")
    @PostMapping("uploadFile")
    public FileVo uploadFile(MultipartFile file) {
        try {
            String returnPath = filePath.getImgPath();
            // 前端限制:视频mp4格式,音频mp3格式,图片jpg,png,gif格式,
            String path = ApplicationContextUtil.BASE_DOWN_FORDER + "image/flowchart/";
            String storedName = UploadFileUtil.uploadFile(file, path);
            return new FileVo(returnPath + "image/flowchart/" + storedName);
        } catch (Exception e) {
            throw new RuntimeException("流程图上传文件失败:" + e);
        }
    }

    @ApiOperation(value = "save", notes = "流程图编辑页面保存接口")
    @PostMapping("save")
    public void save(HttpServletRequest request) {
        try {
            //将传进的参数拆分
            BufferedReader streamReader = new BufferedReader(new InputStreamReader(request.getInputStream(), "UTF-8"));
            StringBuilder builder = new StringBuilder();
            String inputStr;
            while ((inputStr = streamReader.readLine()) != null) {
                builder.append(inputStr);
            }

            JSONObject jsonObject = JSONObject.parseObject(builder.toString());
            FlowChart flowChart = new FlowChart();
            if (!"".equals(jsonObject.getString("id"))) {
                flowChart.setId(jsonObject.getString("id"));
            }
            flowChart.setFlowName(jsonObject.getString("flowName"));
            flowChart.setBelongingItemId(jsonObject.getString("belongingItemId"));
            flowChart.setBelongingItemName(jsonObject.getString("belongingItemName"));
            flowChart.setScienceTagId(jsonObject.getString("scienceTagId"));
            flowChart.setScienceTagName(jsonObject.getString("scienceTagName"));
            flowChart.setChartJson(JSON.parseObject(jsonObject.getString("chartJson")));
            String status = jsonObject.getString("status");
            flowChart.setDeleted(ReleasedFlowChart.UN_DELETE);
            String taskItemId = jsonObject.getString("taskItemId");
            String rejectReason = jsonObject.getString("rejectReason");
            String type = jsonObject.getString("type");
            // 如果归属项目ID为空，则是新增的项目，向rule_item表里插入数据
            // 如果科学分类ID为空，则是新增的科学分类，向rule_item表里插入数据
            if (StringUtils.isBlank(flowChart.getBelongingItemId())) {
                flowChart.setBelongingItemId(getDropDownId("11", flowChart.getBelongingItemName()));
            }
            if (StringUtils.isBlank(flowChart.getScienceTagId())) {
                flowChart.setScienceTagId(getDropDownId("13", flowChart.getScienceTagName()));
            }

            // 如果 id 为空，新增数据   id不为空 修改数据
            if (Integer.parseInt(jsonObject.getString("status")) == ReleasedFlowChart.RELEASE) {
                flowChartService.updateById(flowChart, taskItemId, status, rejectReason, type);
            } else {
                if (StringUtils.isBlank(flowChart.getId())) {
                    flowChart.setVersion(ReleasedFlowChart.UN_DELETE);
                    flowChartService.save(flowChart, taskItemId, status);
                } else {
                    // 修改
                    flowChartService.updateById(flowChart, taskItemId, status, rejectReason, type);
                }
            }
        } catch (Exception e) {
            throw new RuntimeException("保存异常", e);
        }
    }

    private String getDropDownId(String ruleId, String dropDownName) {
        // 根据名称和对应rule表id去查询有没有已经存在的值
        List<RuleItem> list = ruleService.queryItemByNameAndRuleId(ruleId, dropDownName.trim());
        if (CollectionUtils.isEmpty(list)) {
            RuleItem ruleItem = new RuleItem();
            ruleItem.setName(dropDownName);
            ruleItem.setRuleId(ruleId);
            List<RuleItem> valueList = ruleService.queryItemByRuleId(ruleId);
            ruleItem.setIdx(CollectionUtils.isEmpty(valueList) ? 0 : valueList.get(valueList.size() - 1).getIdx() + 1);
            ruleItemService.saveOrUpdate(ruleItem);
            return ruleItem.getId();
        }
        return list.get(0).getId();
    }

    @ApiOperation(value = "selectDetailById", notes = "流程图列表查看详情接口")
    @GetMapping("selectDetailById")
    public ReleasedFlowChart selectDetailById(String id, String status) {
        Map<String, RuleItem> ruleItemMap = ruleItemService.lambdaQuery().list().stream()
                .collect(Collectors.toMap(RuleItem::getId, Function.identity()));
        if ("unpublished".equals(status) || status == null) {
            FlowChart flowChart = flowChartService.getBaseMapper().selectById(id);
            flowChart.setBelongingItemName(ruleItemMap.get(flowChart.getBelongingItemId()).getName());
            flowChart.setScienceTagName(ruleItemMap.get(flowChart.getScienceTagId()).getName());
            return JSON.parseObject(JSON.toJSONString(flowChart), ReleasedFlowChart.class);
        } else {
            ReleasedFlowChart releasedFlowChart = releasedFlowChartService.getBaseMapper().selectById(id);
            releasedFlowChart.setBelongingItemName(ruleItemMap.get(releasedFlowChart.getBelongingItemId()).getName());
            releasedFlowChart.setScienceTagName(ruleItemMap.get(releasedFlowChart.getScienceTagId()).getName());
            return releasedFlowChart;
        }
    }

    @ApiOperation(value = "selectNotExistSameName", notes = "流程图校验名称接口")
    @GetMapping("selectNotExistSameName")
    public boolean selectNotExistSameName(String flowName, String id) {
        // 新增流程图
        int num = flowChartService.queryExistSameName(flowName, id);
        return num == 0 ? true : false;
    }

    @ApiOperation(value = "selectFlowCharList", notes = "流程图查询未发布列表接口")
    @GetMapping("selectFlowCharList")
    public Page<FlowChart> selectFlowCharList(FlowChart flowChart) {
        return flowChartService.queryFlowChartList(flowChart);
    }

    @ApiOperation(value = "selectFlowChartToReleasedFlowChart", notes = "流程图未发布列表发布接口")
    @PostMapping("selectFlowChartToReleasedFlowChart")
    public void selectFlowChartToReleasedFlowChart(String id, String name) {
        flowChartService.flowChart2ReleasedFlowChart(id, name);
    }

    @ApiOperation(value = "selectReleasedFlowCharList", notes = "流程图查询已发布列表接口")
    @GetMapping("selectReleasedFlowCharList")
    public Page<ReleasedFlowChart> selectReleasedFlowCharList(ReleasedFlowChart releasedFlowChart) {
        Page<ReleasedFlowChart> releasedFlowChartPage = flowChartService.queryReleasedFlowChartList(releasedFlowChart);
        for (ReleasedFlowChart flowChart : releasedFlowChartPage.getRecords()) {
            List<TaskItem> taskItemList = taskItemService.getRevisionTaskItemByKnowledgeId(flowChart.getId());
            if (CollectionUtils.isNotEmpty(taskItemList) && taskItemList.size() > 0) {
                flowChart.setIsRevised(ReleasedFlowChart.REVISED);
            }
        }
        return releasedFlowChartPage;
    }

    @ApiOperation(value = "selectionFlowChartToReleased", notes = "流程图批量发布接口")
    @PostMapping("selectionFlowChartToReleased")
    public void selectionFlowChartToReleased(String selection) {
        JSONArray objects = JSONArray.parseArray(selection);
        for (int i = 0; i < objects.size(); i++) {
            JSONObject dataJson = objects.getJSONObject(i);
            String id = dataJson.getString("id");
            String name = dataJson.getString("name");
            try {
                flowChartService.flowChart2ReleasedFlowChart(id, name);
            } catch (Exception e) {
                throw new RuntimeException("流程图批量发布异常" + e);
            }
        }

    }

    @ApiOperation(value = "getAllFlowChartToReleased", notes = "流程图一键发布接口")
    @GetMapping("getAllFlowChartToReleased")
    public void getAllFlowChartToReleased(String flowName,
                                          String createdBy,
                                          String belongingItemId,
                                          String scienceItemId,
                                          String createdTime) {
        FlowChart flowChart = new FlowChart();
        flowChart.setFlowName(flowName);
        flowChart.setCreatedBy(createdBy);
        flowChart.setBelongingItemId(belongingItemId);
        flowChart.setScienceTagId(scienceItemId);
        List<FlowChart> list = flowChartService.queryFlowChart(flowChart, createdTime);

        for (FlowChart flowChart1 : list) {
            try {
                flowChartService.flowChart2ReleasedFlowChart(flowChart1.getId(), flowChart1.getFlowName());
            } catch (Exception e) {
                throw new RuntimeException("流程图一键发布异常:" + e);
            }
        }
    }

    @ApiOperation(value = "selectHistoryById", notes = "流程图查看日志接口")
    @GetMapping("selectHistoryById")
    public List<History> selectHistoryById(String id) {
        return historyMapper.selectList(Wrappers.lambdaQuery(History.class).eq(History::getKnowledgeId, id)
                .orderByDesc(History::getUpdatedTime).orderByAsc(History::getId));
    }

    @ApiOperation(value = "rejectFlowChart", notes = "流程图驳回接口")
    @GetMapping("rejectFlowChart")
    public void rejectFlowChart(String id, String reject) {
        flowChartService.rejectFlowChart(id, reject);
    }

    @ApiOperation(value = "multiInsertTaskItem", notes = "流程图修订接口")
    @PostMapping("multiInsertTaskItem")
    public String multiInsertTaskItem(String reviseType, String selectedKnowledgeIds, String taskId,
                                      String remark, String searchParams) {
        List<ReleasedFlowChart> releasedFlowChartList = null;
        JSONObject searchParamsObj = JSON.parseObject(searchParams);
        String username = PMPHAppUtil.getCurrentUserEnName();
        // 批量修订;
        if (Objects.equals("multi", reviseType)) {
            releasedFlowChartList = releasedFlowChartService.getBaseMapper().executeMultiSelect("select * from released_flow_chart where id in " + selectedKnowledgeIds.replace("[", "(").replace("]", ")"));
        } else {
            // 一键修订, 查询当前搜索条件的知识;
            ReleasedFlowChart releasedFlowChart = new ReleasedFlowChart();
            releasedFlowChart.setFlowName(searchParamsObj.getString("flowName"));
            releasedFlowChart.setCreatedBy(searchParamsObj.getString("createdBy"));
            releasedFlowChart.setBelongingItemId(searchParamsObj.getString("belongingItemId"));
            releasedFlowChart.setScienceTagId(searchParamsObj.getString("scienceItemId"));
            releasedFlowChart.setVersion(searchParamsObj.getInteger("version"));
            releasedFlowChart.setIsRevised(searchParamsObj.getString("isRevised"));
            List<String> list = Lists.newArrayList();
            if (org.apache.commons.lang3.StringUtils.isNotBlank(searchParamsObj.getString("createdTime"))) {
                list.add(searchParamsObj.getString("createdTime").trim().split(",")[0]);
                list.add(searchParamsObj.getString("createdTime").trim().split(",")[1]);
            }
            releasedFlowChart.setQueryCreatedTime(list);
            releasedFlowChartList = flowChartService.queryReleasedFlowChartList(releasedFlowChart).getRecords();
        }
        // 查询当前知识库, 正在编辑的知识;
        String sql = "select * from task_item " +
                " join task on task_item.task_id = task.id " +
                " where task.knowledge_lib_id = '" + KnowledgeLib.FLOW_CHART_LIB_ID + "' " +
                " and task.status != " + Task.STATUS_FINISHED +
                " and task.deleted = 0 " +
                " and task_item.status != " + TaskItem.STATUS_RELEASED;
        List<TaskItem> taskItems = taskItemService.getBaseMapper().executeMultiSelect(sql);
        // taskItems 转为知识id集合
        Set<String> knowledgeInProcessIdSet = taskItems.stream().map(TaskItem::getKnowledgeId).filter(org.apache.commons.lang3.StringUtils::isNotEmpty).collect(Collectors.toSet());

        List<ReleasedFlowChart> finalReleasedFlowChartList = releasedFlowChartList;
        List<String> revisedSuccessList = new ArrayList<>();
        List<String> revisedFailureList = new ArrayList<>();
        for (ReleasedFlowChart releasedFlowChart : finalReleasedFlowChartList) {
            if (!knowledgeInProcessIdSet.contains(releasedFlowChart.getId())) {
                revisedSuccessList.add(releasedFlowChart.getId());
            } else {
                revisedFailureList.add(releasedFlowChart.getId());
            }
        }
        ExecutorServiceFactory.getInstance().submit(() -> flowChartService.multiInsertTaskItem(taskId, remark, username, finalReleasedFlowChartList, knowledgeInProcessIdSet));

        return "修订成功！您修订知识" + revisedSuccessList.size() + "条,请稍后查看任务状态,处在已修订的知识为" + revisedFailureList.size() + "条";

    }

    @ApiOperation(value = "selectSyncList", notes = "流程图查询推送列表接口")
    @PostMapping("selectSyncList")
    public Page<ReleasedFlowChart> selectSyncList(@RequestBody ReleasedFlowChart releasedFlowChart) {
        Page<ReleasedFlowChart> releasedFlowChartIPage = flowChartService.querySyncList(releasedFlowChart);
        return releasedFlowChartIPage;
    }

    @ApiOperation(value = "syncToPlatform", notes = "流程图推送接口")
    @PostMapping("syncToPlatform")
    public void syncToPlatform(@RequestBody ReleasedFlowChart releasedFlowChart) {
        String userName = PMPHAppUtil.getCurrentUserEnName();
        ExecutorServiceFactory.getInstance().submit(() -> {
            flowChartService.syncToPlatform(releasedFlowChart, userName, Const.SYNC_OPERATION_ADD);
        });
    }

    @ApiOperation(value = "selectFlowChartRecycleData", notes = "流程图回收站列表接口")
    @GetMapping("selectFlowChartRecycleData")
    public Page<ReleasedFlowChart> selectFlowChartRecycleData(ReleasedFlowChart releasedFlowChart) {
        LambdaQueryWrapper<ReleasedFlowChart> query = Wrappers.lambdaQuery(ReleasedFlowChart.class)
                .like(StringUtils.isNotBlank(releasedFlowChart.getFlowName()), ReleasedFlowChart::getFlowName, releasedFlowChart.getFlowName())
                .eq(ReleasedFlowChart::getDeleted, Const.DELETED_YES)
                .eq(StringUtils.isNotBlank(releasedFlowChart.getUpdatedBy()), ReleasedFlowChart::getUpdatedBy, releasedFlowChart.getUpdatedBy());
        if (StringUtils.isNotEmpty(releasedFlowChart.getUpdatedTime())) {
            query = query.ge(ReleasedFlowChart::getUpdatedTime, releasedFlowChart.getUpdatedTime().split(",")[0].trim())
                    .le(ReleasedFlowChart::getUpdatedTime, releasedFlowChart.getUpdatedTime().split(",")[1].trim());
        }
        return releasedFlowChartService
                .page(new Page<>(releasedFlowChart.getCurrentPage(), releasedFlowChart.getPageSize()), query);
    }

    @ApiOperation(value = "deleteReleaseFlowChartById", notes = "流程图已发布列表删除接口")
    @GetMapping("deleteReleaseFlowChartById")
    public void deleteReleaseFlowChartById(String id, String status) {
        flowChartService.ReleasedFlowChartDeleteById(id, status);
    }

    @ApiOperation(value = "recoverReleaseFlowChart", notes = "流程图回收站列表恢复接口")
    @PostMapping("recoverReleaseFlowChart")
    public void recoverReleaseFlowChart(String ids) {
        flowChartService.ReleasedFlowChartRecover(ids);
    }

    @ApiOperation(value = "delReleasedFlowChart", notes = "流程图回收站列表彻底删除接口")
    @PostMapping("delReleasedFlowChart")
    public void delReleasedFlowChart(String id, String name, String updatedTime, String updatedBy, String operationType) {
        flowChartService.deleteReleasedFlowChart(id, name, updatedTime, updatedBy, operationType);
    }

    @SneakyThrows
    @ApiOperation(value = "exportFlowChart", notes = "流程图已发布导出接口")
    @GetMapping("exportFlowChart")
    public void exportFlowChart(HttpServletResponse response, String ids, String flowName, String createdBy,
                                String belongingItemId, String scienceItemId, String createdTime,
                                String version) {
        response.setContentType("application/zip");// 指明response的返回对象是文件流
        response.setHeader("Content-Disposition", "attachment;filename=export.zip");
        response.reset();
        if (StringUtils.isBlank(ids)) {
            LambdaQueryWrapper<ReleasedFlowChart> releasedFlowChartQuery = Wrappers.lambdaQuery(ReleasedFlowChart.class).like(StringUtils.isNotBlank(flowName), ReleasedFlowChart::getFlowName, flowName)
                    .eq(StringUtils.isNotBlank(createdBy), ReleasedFlowChart::getCreatedBy, createdBy)
                    .eq(StringUtils.isNotBlank(belongingItemId), ReleasedFlowChart::getBelongingItemId, belongingItemId)
                    .eq(StringUtils.isNotBlank(scienceItemId), ReleasedFlowChart::getScienceTagId, scienceItemId)
                    .eq(StringUtils.isNotBlank(version), ReleasedFlowChart::getVersion, version)
                    .eq(ReleasedFlowChart::getDeleted, ReleasedFlowChart.UN_DELETE);
            if (StringUtils.isNotBlank(createdTime)) {
                releasedFlowChartQuery = releasedFlowChartQuery.ge(ReleasedFlowChart::getUpdatedTime, createdBy.split(",")[0].trim())
                        .le(ReleasedFlowChart::getUpdatedTime, createdBy.split(",")[1].trim());
            }
            List<ReleasedFlowChart> list = releasedFlowChartService.page(new Page<>(), releasedFlowChartQuery).getRecords();

            ids = list.stream().map(ReleasedFlowChart::getId).collect(Collectors.joining(","));
        }
        // 读取模板;
        ZipOutputStream zipOutputStream = null;
        try {
            zipOutputStream = new ZipOutputStream(response.getOutputStream());
            Document template = Jsoup.connect(ApplicationContextUtil.getProperty("static-file.path") + "flowChart/export-flowChart.html").maxBodySize(0).get();
            ClassPathResource classPathResource = null;
            // 写入css模板;
            ZipEntry zipEntry = new ZipEntry("element.css");
            zipOutputStream.putNextEntry(zipEntry);
            classPathResource = new ClassPathResource("public/flowChart/element.css");
            zipOutputStream.write(FileStreamUtil.inputStreamToByte(classPathResource.getInputStream()));
            zipEntry = new ZipEntry("joint.min.css");
            zipOutputStream.putNextEntry(zipEntry);
            classPathResource = new ClassPathResource("public/flowChart/joint.min.css");
            zipOutputStream.write(FileStreamUtil.inputStreamToByte(classPathResource.getInputStream()));

            zipEntry = new ZipEntry("backbone.js");
            zipOutputStream.putNextEntry(zipEntry);
            classPathResource = new ClassPathResource("public/flowChart/backbone.js");
            zipOutputStream.write(FileStreamUtil.inputStreamToByte(classPathResource.getInputStream()));

            zipEntry = new ZipEntry("element.js");
            zipOutputStream.putNextEntry(zipEntry);
            classPathResource = new ClassPathResource("public/flowChart/element.js");
            zipOutputStream.write(FileStreamUtil.inputStreamToByte(classPathResource.getInputStream()));

            zipEntry = new ZipEntry("joint.min.js");
            zipOutputStream.putNextEntry(zipEntry);
            classPathResource = new ClassPathResource("public/flowChart/joint.min.js");
            zipOutputStream.write(FileStreamUtil.inputStreamToByte(classPathResource.getInputStream()));

            zipEntry = new ZipEntry("lodash.js");
            zipOutputStream.putNextEntry(zipEntry);
            classPathResource = new ClassPathResource("public/flowChart/lodash.js");
            zipOutputStream.write(FileStreamUtil.inputStreamToByte(classPathResource.getInputStream()));

            zipEntry = new ZipEntry("jquery.js");
            zipOutputStream.putNextEntry(zipEntry);
            classPathResource = new ClassPathResource("public/flowChart/jquery.js");
            zipOutputStream.write(FileStreamUtil.inputStreamToByte(classPathResource.getInputStream()));

            zipEntry = new ZipEntry("vue.js");
            zipOutputStream.putNextEntry(zipEntry);
            classPathResource = new ClassPathResource("public/flowChart/vue.js");
            zipOutputStream.write(FileStreamUtil.inputStreamToByte(classPathResource.getInputStream()));

            zipEntry = new ZipEntry("fonts/element-icons.ttf");
            zipOutputStream.putNextEntry(zipEntry);
            classPathResource = new ClassPathResource("public/flowChart/fonts/element-icons.ttf");
            zipOutputStream.write(FileStreamUtil.inputStreamToByte(classPathResource.getInputStream()));

            List<ReleasedFlowChart> releasedFlowChartList = new ArrayList<>();
            if (StringUtils.isNotBlank(ids)) {
                for (String id : ids.split(",")) {
                    ReleasedFlowChart releasedFlowChart = releasedFlowChartService.getById(id);
                    releasedFlowChartList.add(releasedFlowChart);
                }
            } else {
                releasedFlowChartList = releasedFlowChartService.list();
            }

            // 不做文件名处理，跟发布时生成的html文件路径保持一直，如果发布时生成的html页面有问题，可以通过该方法重新生成
            for (ReleasedFlowChart releasedFlowChart : releasedFlowChartList) {
                template.body().child(0).text("let showData = " + JSON.toJSONString(releasedFlowChart.getChartJson()));
                template.body().child(1).text("let fileUrl = \"" + StringUtils.substringBeforeLast(ApplicationContextUtil.getProperty("static-file.path"), "/") + "\"");
                zipEntry = new ZipEntry(releasedFlowChart.getId() + ".html");
                zipOutputStream.putNextEntry(zipEntry);
                zipOutputStream.write(StringEscapeUtils.unescapeHtml(template.html()).getBytes());
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            if (null != zipOutputStream) {
                zipOutputStream.closeEntry();
                zipOutputStream.close();
            }
        }
    }
}
